package com.wswy.wzcx.ui.user

import android.arch.lifecycle.Observer
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.module.base.ApiCallback
import com.wswy.wzcx.module.base.onResult
import com.wswy.wzcx.module.validator.ValidatorResult
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.other.PhoneTextWatcher
import com.wswy.wzcx.ui.other.TextWatcherIMPL
import kotlinx.android.synthetic.main.fragment_register.*

/**
 * 手机号输入和短信验证码发送
 * 注册
 * 忘记密码
 * 绑定手机号
 */
class RegisterFragment : BaseVerifyFragment() {


    private lateinit var phoneLayoutController: PhoneLayoutController


    override fun getContentLayoutId(): Int {
        return R.layout.fragment_register
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        loginHolderViewModel = provideViewModelFromActivity(LoginHolderViewModel::class.java)

        phoneLayoutController = PhoneLayoutController(layout_phone,et_phone,img_et_phone_action)
        et_phone.addTextChangedListener(object : TextWatcherIMPL(){
            override fun afterTextChanged(s: Editable?) {
                super.afterTextChanged(s)
                inputCheck()
            }
        })


        //下一步，验证手机号
        btn_next_step.setOnClickListener {


            lockLoad()

            when(loginHolderViewModel.stepState.type){



                LoginHolderViewModel.TYPE_REG-> {
                    regClick()
                }
                LoginHolderViewModel.TYPE_WECHAT_BIND -> {
                    regWechatClick()
                }
                LoginHolderViewModel.TYPE_FORGET_PWD -> {
                    resetPwd()
                }
            }

        }

        resetViews()

        KeyboardUtils.showSoftInput(et_phone)
    }

    private fun regWechatClick(){
        val phone =PhoneTextWatcher.getRealPhoneNumber(et_phone)
        loginHolderViewModel.stepState.phone = phone
        btn_next_step.loading()

        loginHolderViewModel.addRun(Api.get().wechatBindCheck(phone,loginHolderViewModel.stepState.wechatCode).onResult({

            if (isHidden){
                return@onResult
            }

            if (it?.isWechatBind == false){
                //没有绑定，可以注册

                btn_next_step.success{
                    startGVerify()
                }

            }else{

                btn_next_step.fail{
                    unlockLoad()
                }

                //登录状态
                img_et_phone_action.setImageResource(R.drawable.login_warning)
                layout_phone.error = "该号码已绑定其他微信号，请更换手机号码"
            }

        },{
            ApiCallback.toastErrorMsg(it)

            btn_next_step.fail{
                unlockLoad()
            }

        }))

    }

    private fun regClick(){
        val phone =PhoneTextWatcher.getRealPhoneNumber(et_phone)
        loginHolderViewModel.stepState.phone = phone
        btn_next_step.loading()

        loginHolderViewModel.addRun(Api.get().phoneCheck(phone).onResult({

            if (isHidden){
                return@onResult
            }

            if (it?.isExist == false){
                //不存在，可以注册

                btn_next_step.success{
                    startGVerify()
                }

            }else{

                btn_next_step.fail{
                    unlockLoad()
                }

                when(loginHolderViewModel.stepState.type){

                    LoginHolderViewModel.TYPE_REG-> {
                        //登录状态
                        img_et_phone_action.setImageResource(R.drawable.login_warning)
                        layout_phone.error = "该手机号已注册，您可直接登录"
                    }
                    LoginHolderViewModel.TYPE_WECHAT_BIND -> {
                        //微信绑定，已注册，先用手机号登录再绑定
                        startGVerify()
                    }
                }


            }

        },{
            ApiCallback.toastErrorMsg(it)

            btn_next_step.fail{
                unlockLoad()
            }

        }))



    }


    private fun resetPwd(){

        startGVerify()

    }


    /** ----- 短信验证码 */
    override fun onSending() {
        super.onSending()
        lockLoad()
    }

    override fun onSendSuccess() {
        super.onSendSuccess()

        //事件统计 提交手机号，获取验证码
        when(loginHolderViewModel.stepState.type){
            LoginHolderViewModel.TYPE_REG -> {
                sendClickEvent(StatisticsId.u_zc_tj_sjh)
            }
            LoginHolderViewModel.TYPE_WECHAT_BIND->{
                sendClickEvent(StatisticsId.u_wechat_tj_sjh)
            }
            LoginHolderViewModel.TYPE_FORGET_PWD -> {
                sendClickEvent(StatisticsId.u_dl_wjmm_tj_sjh)
            }
        }


        unlockLoad()

        ToastUtils.showText("验证码已发送")

        loginHolderViewModel.clickEvent(LoginHolderViewModel.CLICK_REG_NEXT_VERIFY)
    }

    override fun onSendFail(msg: String?) {
        super.onSendFail(msg)

        unlockLoad()

        ToastUtils.showText(msg)
    }

    /** --- 人机验证 **/
    override fun onGVerifySuccess(ticket: ValidatorResult) {
        super.onGVerifySuccess(ticket)

        val phone =PhoneTextWatcher.getRealPhoneNumber(et_phone)
        sendNext(phone, ticket)

    }

    override fun onGVerifyError() {
        super.onGVerifyError()
        unlockLoad()
    }

    override fun lockLoad() {
        super.lockLoad()

//        et_phone.isEnabled = false
//        btn_next_step.isClickable = false
    }

    override fun unlockLoad() {
        super.unlockLoad()
//        et_phone.isEnabled = true
//        btn_next_step.isClickable = true
//        btn_next_step.isEnabled = true
    }


    private fun sendNext(phone:String,ticket:ValidatorResult){
        loginHolderViewModel.sendSMSVerify(phone,ticket)

    }

    private fun resetViews(){

        unlockLoad()

        btn_next_step.normal()

        loginHolderViewModel.stepState.phone?.let {
            et_phone.setText(it)

            et_phone.setSelection(et_phone.text?.length?:0)
        }?:kotlin.run {
            et_phone.text = null
        }

        when(loginHolderViewModel.stepState.type){

            LoginHolderViewModel.TYPE_REG -> {
                tv_reg.setText(R.string.reg)
                tv_reg_hint.text = "请告诉我们，您的手机号码"
            }

            LoginHolderViewModel.TYPE_FORGET_PWD -> {
                tv_reg.text = "忘记密码"
                tv_reg_hint.text = "请告诉我们，您的手机号码"

            }

            LoginHolderViewModel.TYPE_WECHAT_BIND -> {
                tv_reg.text = "绑定手机号"
                tv_reg_hint.text = "请告诉我们，您的手机号码"

            }

        }


    }

    private fun inputCheck() {
        val text = PhoneTextWatcher.getRealPhoneNumber(et_phone)

        btn_next_step.normal()

        //手机号输入正确
        btn_next_step.isEnabled = !TextUtils.isEmpty(text) && text?.length == 11
    }


    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)

        if (hidden){
            KeyboardUtils.hideSoftInput(et_phone)

        }else{

            resetViews()

            KeyboardUtils.showSoftInput(et_phone)
        }

    }

}